package enhance.plus.util;

import common.core.util.CommonUtil;
import common.core.util.CustomizeRuntimeException;
import lombok.Data;

import java.util.*;

/**
 * @author liubo
 * @created 2020-07-06 14:53
 */
@Data
public class Query {

    /**
     * 条件
     */
    private Criterion criterion;

    /**
     * select 的字段
     */
    private Set<String> selectColumns;

    /**
     * 汇总数据字段
     */
    private String countColumn;
    /**
     * 排序规则
     */
    private List<OrderBy> orderBy;
    /**
     * 分组规则
     */
    private List<String> groupBy;

    /**
     * 初始化
     * @return
     */
    public static Query builder(){
        return new Query();
    }

    /**
     * 构建条件
     * @return
     */
    public static Criterion createCriterion(){
        return new Criterion();
    }

    /**
     * 正序
     * @param columns
     * @return
     */
    public Query ASC(String... columns){
        if(CommonUtil.isEmpty(orderBy)){
            orderBy = new ArrayList<>();
        }
        Query.OrderBy ob = new Query.OrderBy();
        ob.setColumns(columns);
        ob.setSort(QueryUtil.ASC);
        this.orderBy.add(ob);
        return this;
    }

    /**
     * 逆序
     * @param columns
     * @return
     */
    public Query DESC(String... columns){
        if(CommonUtil.isEmpty(orderBy)){
            orderBy = new ArrayList<>();
        }
        Query.OrderBy ob = new Query.OrderBy();
        ob.setColumns(columns);
        ob.setSort(QueryUtil.DESC);
        this.orderBy.add(ob);
        return this;
    }

    /**
     * 分组
     * @param properties
     * @return
     */
    public Query groupBy(String... properties){
        if(CommonUtil.isEmpty(groupBy)){
            groupBy = new ArrayList<>();
        }
        groupBy = Arrays.asList(properties);
        return this;
    }

    /**
     * 需要查询的字段
     * @param properties
     * @return
     */
    public Query selectProperties(String... properties) {
        if (CommonUtil.isNotEmpty(properties)) {
            selectColumns = new HashSet<>(Arrays.asList(properties));
            return this;
        }else {
            throw CustomizeRuntimeException.exception("无效的查询参数");
        }
    }

    @Data
    public class OrderBy{
        private String[] columns;
        private String sort;
    }
}
